package com.atguigu.edu.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.edu.entity.Subject;
import com.atguigu.edu.entity.excel.SubjectData;
import com.atguigu.edu.service.SubjectService;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

//实现监听器进行excel的读取
//不能交给 spring进行管理，需要自己手动去new，不能注入其他对象
public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {

    public SubjectService subjectService;

    //不能交给spring管理，所以不能自动注入service等对象，需要自己手动构造，通过参数传递给监听器，来实现后续的业务逻辑
    public SubjectExcelListener(SubjectService subjectService) {
        this.subjectService = subjectService;
    }

    public SubjectExcelListener() {
    }

    // 读取excel中的内容 一行一行的读取
    @Override
    public void invoke(SubjectData data, AnalysisContext context) {
        if (data == null) {
            throw new GuliException(20001, "文件数据为空");
        }

        //一行一行的读取，每次读取有两个值，第一个值一级分类，第二个值二级分类
        //判断一级分类是否已经在数据库存在
        Subject oneSubject = this.existOneSubject(subjectService, data.getOneSubjectName());

        if (oneSubject == null) {
            //没有相同的一级分类，进行添加
            oneSubject = new Subject();
            System.out.println(oneSubject);
            oneSubject.setParentId("0"); //设置一级分类的 父ID
            oneSubject.setTitle(data.getOneSubjectName()); //设置一级分类的名称
            subjectService.save(oneSubject);
        }

        //获取一级分类的ID值
        String pid = oneSubject.getId();

        Subject twoSubject = this.existTwoSubject(subjectService, data.getTwoSubjectName(), pid);
        if (twoSubject == null) {
            System.out.println(twoSubject);
            twoSubject = new Subject();
            twoSubject.setParentId(pid);
            twoSubject.setTitle(data.getTwoSubjectName());//二级分类的名称
            subjectService.save(twoSubject);
        }

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {

    }

    //判断一级分类，不能重复添加
    private Subject existOneSubject(SubjectService subjectService, String name) {
        QueryWrapper<Subject> wrapper = new QueryWrapper<>();
        wrapper.eq("title", name);
        wrapper.eq("parent_id", "0");

        Subject oneSubject = subjectService.getOne(wrapper);
        return oneSubject;
    }

    //判断二级分类，不能重复添加
    private Subject existTwoSubject(SubjectService subjectService, String name, String pid) {
        QueryWrapper<Subject> wrapper = new QueryWrapper<>();
        wrapper.eq("title", name);
        wrapper.eq("parent_id", pid);

        Subject twoSubject = subjectService.getOne(wrapper);
        return twoSubject;
    }
}
